package controller

import (
	"config"
	"model"
	"net/http"
	"spirit/mongodb"
	"spirit/utils"

	"github.com/dchest/captcha"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

const tbUser = "tbUser"
const infoCollection2 = "infoCollection2"

type LoginController struct {
	Data interface{}
}

func (ctrl *LoginController) Router(router *gin.Engine) {
	router.GET("/", toLogin)
	router.GET("/captcha", Captcha)
	router.GET("/logout", logout)
	router.POST("/login", login)
	loginGroup := router.Group("/system")
	loginGroup.Use(sessionVerify())
	{
		loginGroup.GET("/main", main)
		loginGroup.POST("/main", main)
		loginGroup.POST("/wxysQuery", wxysQuery)
	}
}

func queryYearData(ctx *gin.Context) {
	query := map[string]interface{}{}
	role := GetSessionInfo("role", ctx)
	area := GetSessionInfo("area", ctx).(string)
	year := ctx.Request.FormValue("queryYear")
	m := make(map[string]int, 0)
	indicator := make([]map[string]interface{}, 0)
	tbName := ""
	if year == "" {
		//默认查当前年份
		year = config.CurrentYear
		tbName = config.TbBaseName
		indicator = config.CurrentIndicator
	} else {
		tbName = "infoCollection_" + year
		queryYearIndicator := make(map[string]interface{}, 0)
		queryYearIndicator["year"] = year
		indicator = *(mongodb.Find("indicator", queryYearIndicator, `{"_id":1}`, nil, false, -1, -1))
	}

	for _, val := range indicator {
		m[val["area"].(string)] = int(val["target"].(float64))
	}
	if role == "0" {
		//普通管理员=0,
		query["area"] = area
		current := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)
		resultMap := map[string]interface{}{
			"total":    m[area],
			"current":  current,
			"high":     high,
			"middle":   middle,
			"low":      low,
			"area":     area,
			"areaName": findAreaName(area),
		}
		ctx.JSON(http.StatusOK, resultMap)
	} else if role == "1" {
		//市医院系统管理员
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)

		query2 := map[string]interface{}{}
		finishInfo := make(map[string]int, 0)
		for _, val := range config.CurrentIndicator {
			area := val["area"].(string)
			query2["area"] = area
			finishCount := mongodb.Count(tbName, query2)
			finishInfo[area] = finishCount
		}
		ctx.JSON(http.StatusOK, gin.H{"high": high, "middle": middle, "low": low, "finishInfo": finishInfo, "indicator": config.CurrentIndicator, "currentYear": config.CurrentYear})
	} else if role == "2" {
		//医院神经内科管理员=2(只管理神经内科病人数据)
		tbName = "infoCollection2_" + year
		organCode := GetSessionInfo("organCode", ctx).(string)
		current := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)
		resultMap := map[string]interface{}{
			"current":  current,
			"high":     high,
			"middle":   middle,
			"low":      low,
			"area":     area,
			"areaName": getAreaNameByCode(organCode),
		}
		ctx.JSON(http.StatusOK, resultMap)
	}
}

func Captcha(ctx *gin.Context) {
	id := captcha.NewLen(4) //此id为生成验证码的ID，并不是实际显示的数字，在提交校验时，需要根据此ID进行查询。
	//校验时调用以下代码
	//ccid,_:=c.GetSession("CheckCodeId").(string)
	//captcha.VerifyString(ccid,"用户输入的校验码")//返回bool
	session := sessions.Default(ctx)
	session.Set("CheckCodeId", id)
	session.Save()
	w := ctx.Writer
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")
	w.Header().Set("Content-Type", "image/png")
	captcha.WriteImage(w, id, 120, 50)
}
func logout(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Clear()
	session.Save()
	ctx.HTML(http.StatusOK, "login.html", nil)
}
func toLogin(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "login.html", nil)
}

/*危险因素构成统计查询*/
func wxysQuery(ctx *gin.Context) {
	area := ctx.Request.FormValue("area")
	year := ctx.Request.FormValue("queryYear")
	role := GetSessionInfo("role", ctx)
	b := false
	if role == "0" && area != "" {
		b = true
	}
	if year == "" {
		//默认查当前年份
		year = config.CurrentYear
	}
	tbName := "infoCollection_" + year
	if role == "2" {
		tbName = "infoCollection2_" + year
	}

	/*高血压*/
	query1 := map[string]interface{}{}
	query1["ccRiskRating.fengxianpingji_gaoxueya"] = "有"
	if b {
		query1["area"] = area
	}
	gaoxueya := mongodb.Count(tbName, query1)

	/*血脂异常*/
	query2 := map[string]interface{}{}
	if b {
		query2["area"] = area
	}
	query2["ccRiskRating.fengxianpingji_xzyc"] = "是"
	xzyc := mongodb.Count(tbName, query2)

	/*糖尿病*/
	query3 := map[string]interface{}{}
	if b {
		query3["area"] = area
	}
	query3["ccRiskRating.fengxianpingji_tnb"] = "有"
	tnb := mongodb.Count(tbName, query3)

	/*房颤或瓣膜性心脏病*/
	query4 := map[string]interface{}{}
	if b {
		query4["area"] = area
	}
	query4["ccRiskRating.fengxianpingji_fc"] = "有"
	fc := mongodb.Count(tbName, query4)

	/*吸烟史*/
	query5 := map[string]interface{}{}
	if b {
		query5["area"] = area
	}
	query5["ccRiskRating.fengxianpingji_xiyan"] = "有"
	xiyan := mongodb.Count(tbName, query5)

	/*明显超重或肥胖*/
	query6 := map[string]interface{}{}
	if b {
		query6["area"] = area
	}
	query6["ccRiskRating.fengxianpingji_chaozhong"] = "是"
	chaozhong := mongodb.Count(tbName, query6)

	/*运动缺乏*/
	query7 := map[string]interface{}{}
	if b {
		query7["area"] = area
	}
	query7["ccRiskRating.fengxianpingji_yundong"] = "是"
	yundong := mongodb.Count(tbName, query7)

	/*脑卒中家族史*/
	query8 := map[string]interface{}{}
	if b {
		query8["area"] = area
	}
	query8["ccRiskRating.fengxianpingji_naocuzhong_family_history"] = "有"
	naocuzhong_family_history := mongodb.Count(tbName, query8)

	ctx.JSON(http.StatusOK, map[string]interface{}{
		"gaoxueya":                  gaoxueya,
		"xzyc":                      xzyc,
		"tnb":                       tnb,
		"fc":                        fc,
		"xiyan":                     xiyan,
		"chaozhong":                 chaozhong,
		"yundong":                   yundong,
		"naocuzhong_family_history": naocuzhong_family_history,
	})

}

func main(ctx *gin.Context) {
	query := map[string]interface{}{}
	role := GetSessionInfo("role", ctx)
	area := GetSessionInfo("area", ctx).(string)
	year := ctx.Request.FormValue("queryYear")
	m := make(map[string]int, 0)
	indicator := make([]map[string]interface{}, 0)
	if year == "" {
		//默认查当前年份
		year = config.CurrentYear
		indicator = config.CurrentIndicator
	} else {
		queryYearIndicator := make(map[string]interface{}, 0)
		queryYearIndicator["year"] = year
		indicator = *(mongodb.Find("indicator", queryYearIndicator, `{"_id":1}`, nil, false, -1, -1))
	}
	tbName := "infoCollection_" + year
	for _, val := range indicator {
		m[val["area"].(string)] = int(val["target"].(float64))
	}

	if role == "0" {
		//普通管理员=0,
		query["area"] = area
		current := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)
		resultMap := map[string]interface{}{
			"total":    m[area],
			"current":  current,
			"high":     high,
			"middle":   middle,
			"low":      low,
			"area":     area,
			"areaName": findAreaName(area),
		}
		ctx.HTML(http.StatusOK, "main1.html", resultMap)
	} else if role == "1" {
		//市医院系统管理员
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)

		query2 := map[string]interface{}{}
		finishInfo := make(map[string]int, 0)
		for _, val := range indicator {
			area := val["area"].(string)
			query2["area"] = area
			finishCount := mongodb.Count(tbName, query2)
			finishInfo[area] = finishCount
		}
		ctx.HTML(http.StatusOK, "main.html", gin.H{"high": high, "middle": middle, "low": low, "finishInfo": finishInfo, "indicator": indicator, "queryYear": year})
	} else if role == "2" {
		//医院神经内科管理员=2(只管理神经内科病人数据)
		tbName = "infoCollection2_" + year
		organCode := GetSessionInfo("organCode", ctx).(string)
		current := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "高危"
		high := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "中危"
		middle := mongodb.Count(tbName, query)
		query["ccRiskRating.risk_level"] = "低危"
		low := mongodb.Count(tbName, query)
		resultMap := map[string]interface{}{
			"current":  current,
			"high":     high,
			"middle":   middle,
			"low":      low,
			"area":     area,
			"areaName": getAreaNameByCode(organCode),
		}
		ctx.HTML(http.StatusOK, "main2.html", resultMap)
	}
}

func findAreaName(area string) string {
	for _, val := range config.Organs {
		if val["organCode"] == area {
			return val["organName"].(string)
		}
	}
	return ""
}

func login(ctx *gin.Context) {
	result := &model.BaseResult{}
	account := ctx.Request.FormValue("account")
	password := ctx.Request.FormValue("password")
	_captcha := ctx.Request.FormValue("_captcha")

	ccid, _ := GetSessionInfo("CheckCodeId", ctx).(string)
	b := captcha.VerifyString(ccid, _captcha) //返回bool
	if !b {
		result.Code = 3
		result.Msg = "验证码错误"
		ctx.HTML(http.StatusOK, "login.html", gin.H{"code": result.Code, "msg": result.Msg})
		return
	}
	session := sessions.Default(ctx)
	_account := session.Get("account")
	_role := session.Get("role")
	if _account != nil && _role != nil {
		if _account == account {
			ctx.Redirect(http.StatusMovedPermanently, "/system/main")
			return
		}
	}

	query := map[string]interface{}{}
	query["account"] = account
	query["password"] = utils.GetMd5String(password)
	m := mongodb.FindOne(tbUser, query)
	if m != nil && len(*m) > 0 {
		//fmt.Println("登录查询出来:", m)
		d := *m
		id := utils.BsonIdToSId(d["_id"])
		role := utils.SafeConvert2String(d["role"])
		area := utils.SafeConvert2String(d["area"])
		organName := utils.SafeConvert2String(d["organName"])
		organCode := utils.SafeConvert2String(d["organCode"])
		name := utils.SafeConvert2String(d["name"])
		session := sessions.Default(ctx)
		session.Set("role", role)
		session.Set("name", name)
		session.Set("organName", organName)
		session.Set("organCode", organCode)
		session.Set("area", area)
		session.Set("account", account)
		session.Set("id", id)
		if err := session.Save(); err == nil {
			result.Code = 0
			result.Msg = "登录成功"
			ctx.Redirect(http.StatusMovedPermanently, "/system/main")
			return
		} else {
			result.Code = 2
			result.Msg = "登录未知错误,稍后重试"
		}
	} else {
		result.Code = 1
		result.Msg = "用户名密码错误"
	}
	ctx.HTML(http.StatusOK, "login.html", gin.H{"code": result.Code, "msg": result.Msg})
}
